<template>
  <d2-container class="page">
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-dialog
      :title="createOrEdit"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" ref="form">
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.realName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-select v-model="form.roleId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="照片" :label-width="formLabelWidth">
          <el-upload
            action="https://xcx.ruiysoft.com/reserve/qiniu/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :limit="9"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth">
          <el-input v-model="form.intro" autocomplete="off" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateNew('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- <el-button type="primary" size="mini" @click="showCreateDlg('form')">新建</el-button> -->
    <el-button type="primary" size="mini" @click="refresh">刷新</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column label="昵称" width="250">
        <template slot-scope="scope">{{ scope.row.nickName }}</template>
      </el-table-column>
      <el-table-column label="头像">
        <template slot-scope="scope">
          <img v-bind:src="scope.row.avatarUrl" style="width:35%">
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">{{ scope.row.realName }}</template>
      </el-table-column>
      <el-table-column label="手机">
        <template slot-scope="scope">{{ scope.row.mobile }}</template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template
          slot-scope="scope"
        >{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showEditDlg(scope.row)" icon="el-icon-edit"></el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete"></el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination background="" layout="prev, pager, next" :total="50"></el-pagination>
  </d2-container>
</template>

<script>
import {
  fetchList,
  createOrEdit,
  queryById,
  deleteById
} from "@/api/sys.sales";

import * as dict from "@/api/sys.dict";

export default {
  components: {},
  data() {
    return {
      options: [],
      fileList: [],
      tableData: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        name: "",
        mobile: "",
        intro: ""
      },
      formLabelWidth: "100px",
      dialogImageUrl: "",
      dialogVisible: false,
      createOrEdit: "",
      downloadPath: ""
    };
  },
  filters: {
    parseTime: function(time, cFormat) {
      time = Date.parse(new Date(time));
      if (arguments.length === 0) {
        return null;
      }

      if ((time + "").length === 10) {
        time = +time * 1000;
      }

      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        date = new Date(parseInt(time));
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a")
          return ["一", "二", "三", "四", "五", "六", "日"][value - 1];
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return timeStr;
    }
  },
  mounted() {
    this.getList();
    
    dict.fetchList("{parentCode: 'roleType'}").then(resp => {
      this.options = resp.data;
    });
  },
  methods: {
    refresh() {
      this.getList();
    },

    showCreateDlg(formName) {
      this.dialogFormVisible = true;
      this.createOrEdit = "新建";
      // this.$refs[formName].resetFields();
    },

    showEditDlg(row) {
      this.dialogFormVisible = true;
      this.createOrEdit = "编辑";
      this.form = row;
      this.form.roleId = String(row.roleId);

      this.fileList = [];
      row.photographList.forEach(element => {
        this.fileList.push({ url: element });
      });
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.success);
      // this.downloadPath = response.downloadPath;
      this.fileList.push({ url: response.downloadPath });
    },

    handleCreateNew(formName) {
      let that = this;

      const set = that.$refs;
      set[formName].validate(valid => {
        if (valid) {
          let tmp = [];
          that.fileList.forEach(element => {
            if(element.url != null)
              tmp.push(element.url);
          });
          that.form.photographList = tmp;
          createOrEdit(that.form).then(() => {
            that.dialogFormVisible = false;
            that.getList();
            that.$notify({
              title: "成功",
              message: "操作成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },

    getList() {
      fetchList({roleId: 3}).then(response => {
        if (response.success) this.tableData = response.data;
      });
    },

    handleRemove(file, _fileList) {
      // console.log(file, _fileList);
      const index = this.fileList.indexOf(file, 0);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleDelete(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteById(row.id)
          .then(() => {
            this.getList();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .catch(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  .logo {
    width: 120px;
  }
  .btn-group {
    color: $color-text-placehoder;
    font-size: 12px;
    line-height: 12px;
    margin-top: 0px;
    margin-bottom: 20px;
    .btn-group__btn {
      color: $color-text-sub;
      &:hover {
        color: $color-text-main;
      }
      &.btn-group__btn--link {
        color: $color-primary;
      }
    }
  }
}
</style>
